﻿using Microsoft.Extensions.Logging;
using MiniJob.Worker.Jobs;

namespace MiniJob.Worker.Runtime;

internal sealed class JobManager
{
    private readonly JobRegistration registration;
    private readonly JobActivator activator;
    private readonly ILogger logger;

    internal JobManager(JobRegistration registration, ILoggerFactory loggerFactory, JobActivator activator)
    {
        this.registration = registration;
        this.activator = activator;

        this.logger = loggerFactory.CreateLogger(this.GetType());
    }

    internal JobTypeInformation JobTypeInfo => this.registration.Type;

    internal async Task RunJobAsync(JobContext jobContext, CancellationToken cancellationToken = default)
    {
        var state = await CreateJobAsync();
        await state.Job.ExecuteAsync(jobContext, cancellationToken);
    }

    private async Task<JobActivatorState> CreateJobAsync()
    {
        this.logger.LogDebug("Creating Job of type {JobType}", this.JobTypeInfo.ImplementationType);
        var state = await this.activator.CreateAsync();
        this.logger.LogDebug("Finished creating Job of type {JobType}", this.JobTypeInfo.ImplementationType);
        return state;
    }
}
